package net.area80.file
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	//import pickatrip.utils.Path;

	/**
	 * PHPImageBrowser
	 * @author Wissarut Pimanmassuriya
	 */
	public class PHPImageBrowser extends AbstractImageBrowser
	{

		private var fileRef:FileReference;

		public static var UPLOAD_PATH:String = "upload.php";
		public static var DIR_NAME:String = "uploadimages";
		public static var SITE_ABSOLUTE_PATH:String = "";

		public var state:String = "upload";
		public var fileName:String = "";
		public var fileSize:uint = 200;

		private const fileNameChars:String = "0123456789abcdefghijklmnopqrstuvwxyz";


		public function PHPImageBrowser(type:/*FileFilter*/Array, size:int = 0, smoothing:Boolean = false):void
		{
			super(type, size, smoothing);

		}

		private function getFileName():String
		{
			var str:String = String(new Date().getTime());
			for (var i:uint = 0; i < 5; i++)
			{
				str = str + fileNameChars.charAt(Math.round(Math.random() * (fileNameChars.length - 1)));
			}
			return str + ".jpg";
		}

		override public function browse():void
		{
			state = "upload";

			if (!type || type.length == 0)
				dispatchErrorEvent("File type doesn't set yet");
			fileRef = new FileReference();

			fileRef.addEventListener(Event.SELECT, fileSelect);
			fileRef.addEventListener(Event.OPEN, openHandler);
			fileRef.addEventListener(Event.CANCEL, cancelHandler);
			fileRef.addEventListener(Event.COMPLETE, completeHandler);
			fileRef.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);

			fileRef.browse(type);

		}

		private function openHandler(e:Event):void
		{
			dispatchEvent(e);
		}

		private function cancelHandler(e:Event):void
		{
			dispatchEvent(e);
		}

		private function downloadName():void
		{
		/*trace("request from : " + UPLOAD_GET_PICNAME);

		   var request:URLRequest = new URLRequest();
		   request.url = UPLOAD_GET_PICNAME;
		   request.method = URLRequestMethod.POST;
		   var loader:URLLoader = new URLLoader();
		   loader.dataFormat = URLLoaderDataFormat.TEXT;
		   loader.addEventListener(Event.COMPLETE, getPathFileCompleted);
		 loader.load(request);*/


		}

		private function getPathFileCompleted(e:Event):void
		{
			var loader:URLLoader = URLLoader(e.target);
			var loaderReturn:URLVariables = new URLVariables(loader.data);
			try
			{
				trace("\t----- Recived FileName, downoading the file -----------------------------------");
				trace(SITE_ABSOLUTE_PATH + DIR_NAME + "/" + loaderReturn.pic_name);
				state = "download";
				loadFile(SITE_ABSOLUTE_PATH + DIR_NAME + "/" + loaderReturn.pic_name);

			}
			catch (error:Error)
			{
				trace("Unable to load URL");
				dispatchErrorEvent("Unable to load URL " + SITE_ABSOLUTE_PATH + DIR_NAME + "/" + loaderReturn.pic_name);
			}
		}

		private function completeHandler(e:Event):void
		{
			e.target.removeEventListener(Event.COMPLETE, completeHandler);
			//downloadName();
			doDownloadFile();
			//trace(e);
		}

		private function doDownloadFile():void
		{
			//trace("\t----- Downoading the File -----------------------------------");
		//	trace(SITE_ABSOLUTE_PATH + DIR_NAME + "/" + fileName);
			state = "download";
			loadFile(SITE_ABSOLUTE_PATH + DIR_NAME + "/" + fileName);
		}


		private function ioErrorHandler(e:IOErrorEvent):void
		{
			//trace(e);
		}

		protected override function progressHandler(e:ProgressEvent):void
		{
			var ev:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS);
			if (state == "upload")
			{
				ev.bytesTotal = e.bytesTotal;
				ev.bytesLoaded = e.bytesLoaded * 0.5;
				dispatchEvent(ev);
			}
			else if (state == "download")
			{
				ev.bytesTotal = e.bytesTotal;
				ev.bytesLoaded = (e.bytesTotal * 0.5) + (e.bytesLoaded * 0.5);
				dispatchEvent(ev);
			}
		}

		private function securityErrorHandler(e:Event):void
		{
			//trace(e);
		}

		private function fileSelect(e:Event):void
		{
		
			state = "upload";

			if (fileRef.size > fileSize * 1024)
			{
				var msg:String="File size must less than ";
				if(fileSize>=1000) {
					msg += fileSize*0.001+"Mb";
				} else {
					msg += fileSize+"kb"
				}
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, msg));
			}
			else
			{
				fileName = getFileName();
				dispatchEvent(new Event(Event.SELECT)); 
				//	trace("upload"+SITE_ABSOLUTE_PATH + UPLOAD_PATH + "?filename=" + fileName + "&dirname=" + DIR_NAME)
				fileRef.upload(new URLRequest(SITE_ABSOLUTE_PATH + UPLOAD_PATH + "?filename=" + fileName + "&dirname=" + DIR_NAME));
			}
		}



	}

}